#!/bin/bash

# 创建证书目录
mkdir -p certs

# 生成CA私钥
openssl genrsa -out certs/ca-key.pem 4096

# 生成CA证书
openssl req -new -x509 -key certs/ca-key.pem -sha256 -subj "/C=CN/ST=Beijing/L=Beijing/O=ConfigMonitor/CN=ConfigMonitor-CA" -days 3650 -out certs/ca-cert.pem

# 生成Server私钥
openssl genrsa -out certs/server-key.pem 4096

# 生成Server证书签名请求
openssl req -subj "/C=CN/ST=Beijing/L=Beijing/O=ConfigMonitor/CN=1.14.199.50" -sha256 -new -key certs/server-key.pem -out certs/server.csr

# 创建Server证书扩展文件
cat > certs/server-extfile.cnf <<EOF
subjectAltName = IP:1.14.199.50,DNS:localhost
extendedKeyUsage = serverAuth
EOF

# 生成Server证书
openssl x509 -req -days 365 -sha256 -in certs/server.csr -CA certs/ca-cert.pem -CAkey certs/ca-key.pem -out certs/server-cert.pem -extfile certs/server-extfile.cnf -CAcreateserial

# 生成Client私钥
openssl genrsa -out certs/client-key.pem 4096

# 生成Client证书签名请求
openssl req -subj "/C=CN/ST=Beijing/L=Beijing/O=ConfigMonitor/CN=8.155.160.173" -new -key certs/client-key.pem -out certs/client.csr

# 创建Client证书扩展文件
cat > certs/client-extfile.cnf <<EOF
subjectAltName = IP:8.155.160.173,DNS:localhost
extendedKeyUsage = clientAuth
EOF

# 生成Client证书
openssl x509 -req -days 365 -sha256 -in certs/client.csr -CA certs/ca-cert.pem -CAkey certs/ca-key.pem -out certs/client-cert.pem -extfile certs/client-extfile.cnf -CAcreateserial

# 清理临时文件
rm certs/server.csr certs/client.csr certs/server-extfile.cnf certs/client-extfile.cnf

# 设置权限
chmod 600 certs/*-key.pem
chmod 644 certs/*-cert.pem certs/ca-cert.pem

echo "证书生成完成！"
echo "CA证书: certs/ca-cert.pem"
echo "Server证书: certs/server-cert.pem"
echo "Server私钥: certs/server-key.pem"
echo "Client证书: certs/client-cert.pem"
echo "Client私钥: certs/client-key.pem"